package org.xyl.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.xyl.dto.DiagnosisRequest;
import org.xyl.dto.DiagnosisResponse;
import org.xyl.model.KnowledgeDocument;
import org.xyl.service.RagService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * RAG控制器
 */
@RestController
@RequestMapping("/api/rag")
public class RagController {
    
    private static final Logger logger = LoggerFactory.getLogger(RagController.class);
    
    @Autowired
    private RagService ragService;
    
    /**
     * 初始化知识库
     */
    @PostMapping("/knowledge/initialize")
    public ResponseEntity<Map<String, String>> initializeKnowledgeBase() {
        try {
            logger.info("初始化知识库请求");
            ragService.initializeKnowledgeBase();
            
            Map<String, String> response = new HashMap<>();
            response.put("status", "success");
            response.put("message", "知识库初始化成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("知识库初始化失败", e);
            
            Map<String, String> response = new HashMap<>();
            response.put("status", "error");
            response.put("message", "知识库初始化失败: " + e.getMessage());
            
            return ResponseEntity.status(500).body(response);
        }
    }
    
    /**
     * 添加文档到知识库
     */
    @PostMapping("/knowledge/documents")
    public ResponseEntity<Map<String, String>> addDocuments(@RequestBody List<KnowledgeDocument> documents) {
        try {
            logger.info("添加文档请求，数量: {}", documents.size());
            ragService.addDocuments(documents);
            
            Map<String, String> response = new HashMap<>();
            response.put("status", "success");
            response.put("message", "文档添加成功");
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("添加文档失败", e);
            
            Map<String, String> response = new HashMap<>();
            response.put("status", "error");
            response.put("message", "文档添加失败: " + e.getMessage());
            
            return ResponseEntity.status(500).body(response);
        }
    }
    
    /**
     * 执行设备诊断
     */
    @PostMapping("/diagnosis")
    public ResponseEntity<DiagnosisResponse> performDiagnosis(@RequestBody DiagnosisRequest request) {
        try {
            logger.info("执行诊断请求: 设备ID={}", request.getDeviceId());
            DiagnosisResponse response = ragService.performDiagnosis(request);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("诊断失败", e);
            
            DiagnosisResponse errorResponse = new DiagnosisResponse();
            errorResponse.setDeviceId(request.getDeviceId());
            errorResponse.setStatus("ERROR");
            errorResponse.setConfidenceScore("0%");
            
            return ResponseEntity.status(500).body(errorResponse);
        }
    }
    
    /**
     * 获取问题解决方案
     */
    @GetMapping("/solution/{problemCode}")
    public ResponseEntity<Map<String, String>> getSolution(@PathVariable String problemCode, 
                                                          @RequestParam(required = false) String context) {
        try {
            logger.info("获取解决方案请求: 问题代码={}", problemCode);
            String solution = ragService.generateSolution(problemCode, context != null ? context : "");
            
            Map<String, String> response = new HashMap<>();
            response.put("status", "success");
            response.put("problemCode", problemCode);
            response.put("solution", solution);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            logger.error("获取解决方案失败", e);
            
            Map<String, String> response = new HashMap<>();
            response.put("status", "error");
            response.put("message", "获取解决方案失败: " + e.getMessage());
            
            return ResponseEntity.status(500).body(response);
        }
    }
    
    /**
     * 健康检查
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, String>> healthCheck() {
        Map<String, String> response = new HashMap<>();
        response.put("status", "healthy");
        response.put("service", "pricetag-rag-system");
        
        return ResponseEntity.ok(response);
    }
}